﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace iNet.Tasks
{
	class WaitEvent
	{
		#region 欄位
		volatile bool _IsSet;
		readonly object _SyncRoot = new object();
		#endregion
		#region 建構子
		public WaitEvent()
		{ }
		public WaitEvent(bool isSet)
		{
			_IsSet = isSet;
		}
		#endregion
		#region Reset
		public void Reset()
		{
			lock (_SyncRoot)
			{
				_IsSet = false;
			}
		}
		#endregion
		#region Set
		public void Set()
		{
			lock (_SyncRoot)
			{
				if (!_IsSet)
				{
					_IsSet = true;
					Monitor.PulseAll(_SyncRoot);
				}
			}
		}
		#endregion
		#region Wait
		public void Wait()
		{
			this.Wait(Timeout.Infinite);
		}
		public bool Wait(int timeoutMillis)
		{
			lock (_SyncRoot)
			{
				if (_IsSet)
					return true;
				return Monitor.Wait(_SyncRoot, timeoutMillis);
			}
		}
		#endregion
	}
}
